package org.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author xuelongjiang
 *
 * 反射工具类
 */
public class ReflectUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectUtil.class);

    /**
     * 实例类
     */
    public static Object newInstance(Class<?> cls){

        Object obj;
        try {
            obj = cls.newInstance();
        }catch (Exception e){
            LOGGER.error("class instance fail",e);
            throw  new RuntimeException(e);
        }
        return obj;
    }


    /**
     * 反射调用方法
     */
    public static Object invokeMethod(Object obj, Method method,Object ... args){

        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj,args);
        }catch (Exception e){
            LOGGER.error("invoke method fail",e);
            throw  new RuntimeException(e);
        }
        return result;
    }


    /**
     * 反射设置域的值
     */
    public static void setFile(Object obj, Field field,Object value){

        try {
            field.setAccessible(true);
            field.set(obj,value);
        } catch (Exception e){
            LOGGER.error("reflect set feild fail",e);
            throw  new RuntimeException();
        }
    }

}
